package cn.roderick.web.controller;

import cn.roderick.common.controller.BaseController;
import cn.roderick.log.LogManager;
import cn.roderick.log.factory.LogTaskFactory;
import cn.roderick.shiro.ShiroKit;
import cn.roderick.shiro.ShiroUser;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import static cn.roderick.core.HttpKit.getIp;

@Controller
public class LoginController extends BaseController{

//    @RequestMapping(value = "/",  method = RequestMethod.GET)
//    public String index(){
//        return "/login.html";
//    }

    /**
     * 跳转到登录页面
     */
    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public String login() {
            if (ShiroKit.isAuthenticated() || ShiroKit.getUser() != null) {
            return REDIRECT + "/";
        } else {
            return "/login.html";
        }
    }

    /**
     * 点击登录执行的动作
     */
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public String loginValid() {
        String username = super.getParam("username").trim();
        String password = super.getParam("password").trim();
        String remember = super.getParam("remember");

        //验证验证码是否正确
//        if (ToolUtil.getKaptchaOnOff()) {
//            String kaptcha = super.getParam("kaptcha").trim();
//            String code = (String) super.getSession().getAttribute(Constants.KAPTCHA_SESSION_KEY);
//            if (ToolUtil.isEmpty(kaptcha) || !kaptcha.equals(code)) {
//                throw new InvalidKaptchaException();
//            }
//        }
//
        Subject currentUser = ShiroKit.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(username, password.toCharArray());
//
//        if ("on".equals(remember)) {
//            token.setRememberMe(true);
//        } else {
//            token.setRememberMe(false);
//        }
//
        currentUser.login(token);
//
        ShiroUser shiroUser = ShiroKit.getUser();
        super.getSession().setAttribute("shiroUser", shiroUser);
        super.getSession().setAttribute("username", shiroUser.getAccount());

        LogManager.me().executeLog(LogTaskFactory.loginLog(shiroUser.getId(), getIp()));

        ShiroKit.getSession().setAttribute("sessionFlag", true);

        return REDIRECT + "/";
    }


}
